package src.lshz.servlet;

import src.lshz.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/lshzlogin")
public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 使用 Request 的 getParameter 方法获取查询字符串中键为 u 的值
		String username = req.getParameter("u");
		// 使用 Request 的 getParameter 方法获取查询字符串中键为 p 的值
		String password = req.getParameter("p");
		System.out.println("username = " + username);
		System.out.println("password = " + password);
		// 使用 Request 的 getParameter 方法获取查询字符串中键为 c 的值
		String code = req.getParameter("c");

		HttpSession session = req.getSession();
		Object ccc = session.getAttribute("CCC");
		boolean isTrue = code != null && code.equals(ccc);
		if (!isTrue) {
			// 输入的验证码和存储在 session 中的验证码的值不一致
			PrintWriter writer = resp.getWriter();
			writer.write("crroode is er");
			writer.flush();
			writer.close();
			return;
		}


		// 查询数据库，验证账号密码的存在性
		String sql = "SELECT id FROM `user` WHERE username = ? AND `password` = MD5(?)";
		Long id = JdbcUtils.select(sql, Long.class, username, password);
		if (id != null && id > 0) {
			// 当凭借账号和密码成功查询到 id 的时候，将其存储到 session 中
			session.setAttribute("UID", id);
			// 重定向到首页
			resp.sendRedirect("/lshz/index.jsp");
		} else {
			// 重定向到登录页
			resp.sendRedirect("/lshz/login.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
